package leetcode;

/**
 * 描述:
 *
 * @author Madison You
 * @created 23:23
 */
public class Mid_34_SearchRange {
    public static void main(String[] args) {
        int[] ints = {5,7,7,8,8,10};
        int[] ints1 = new Mid_34_SearchRange().searchRange(ints, 9);
        System.out.println(ints1);
    }

    public int[] searchRange(int[] nums, int target) {
        int index = binarySearch(nums, target);
        if (index == -1) {
            return new int[]{-1, -1};
        }
        int left = index;
        int right = index;
        while (left-1 >= 0 && nums[index] == nums[left - 1]) {
            left--;
        }
        while (right + 1 < nums.length && nums[right + 1] == nums[index]) { // 防止数组越界。
            right++;
        }
        return new int[]{left, right};
    }

    public int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1; // 不变量：左闭右闭区间

        while (left <= right) { // 不变量：左闭右闭区间
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1; // 不变量：左闭右闭区间
            }
        }
        return -1; // 不存在
    }
    
}
